import logging
import logging.handlers
import os

_inited = False  # 初始化标志


def init(filename=None, fmt=None, level=None, console=True):
    """
    初始化日志系统（单文件）
    :param filename:
    :param fmt:
    :param level:
    :param console:
    :return:
    """
    _init_logger(filename, fmt, level, console)


def init_daily(filename=None, fmt=None, level=None, console=True):
    """
    初始化日志系统（每日滚动业务）
    :param filename:
    :param fmt:
    :param level:
    :param console:
    :return:
    """
    _init_logger(filename, fmt, level, console, 2)


def set_level(level='INFO'):
    logging.getLogger().setLevel(level)


def _init_logger(filename=None, fmt=None, level=None, console=True, cate=1):
    global _inited
    if _inited:
        return

    _create_log_dir(filename)

    date_fmt = '%Y-%m-%d %H:%M:%S'

    if not fmt:
        fmt = '%(levelname)-5s %(asctime)s [%(thread)d] [%(filename)s=>%(funcName)s():%(lineno)d] - %(message)s'

    if not level:
        level = logging.INFO

    if cate == 1:
        _init_file_logger(level, date_fmt, fmt, filename, console)

    elif cate == 2:
        _init_daily_file_logger(level, date_fmt, fmt, filename, console)

    _inited = True


# 创建日志目录
def _create_log_dir(filename: str):
    if not filename:
        return

    path, name = os.path.split(filename)
    path = os.path.abspath(path)

    if not os.path.exists(path) or not os.path.isdir(path):
        os.makedirs(path)


def _create_console_handler(level, date_fmt, fmt):
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(logging.Formatter(fmt, date_fmt))

    if level:
        console_handler.setLevel(level)

    return console_handler


def _create_rolling_handler(level, date_fmt, fmt, filename):
    daily_handler = logging.handlers.TimedRotatingFileHandler(filename=filename, when='D', interval=1, backupCount=7)
    daily_handler.setFormatter(logging.Formatter(fmt, date_fmt))

    if level:
        daily_handler.setLevel(level)  # 也可以不设置，不设置就默认用logger的level

    return daily_handler


def _init_daily_file_logger(level, date_fmt, fmt, filename, console):
    handlers = [_create_rolling_handler(level, date_fmt, fmt, filename)]
    if console:
        handlers.append(_create_console_handler(level, date_fmt, fmt))

    logging.basicConfig(level=level, datefmt=date_fmt, format=fmt, handlers=handlers)


def _init_file_logger(level, date_fmt, fmt, filename, console):
    logging.basicConfig(level=level, datefmt=date_fmt, format=fmt, filename=filename)

    if filename and console:
        # 输出到控制台的 handler
        logging.getLogger().addHandler(_create_console_handler(level, date_fmt, fmt))
